package com.kinglumi.ailighting.auth.service.biz;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kinglumi.ailighting.auth.base.BaseService;
import com.kinglumi.ailighting.auth.base.Query;
import com.kinglumi.ailighting.auth.bo.ApiResult;
import com.kinglumi.ailighting.auth.constant.ServiceErrorEnum;
import com.kinglumi.ailighting.auth.entity.MeshInfo;
import com.kinglumi.ailighting.auth.entity.MeshUserLink;
import com.kinglumi.ailighting.auth.entity.UserDetail;
import com.kinglumi.ailighting.auth.entity.UserInfo;
import com.kinglumi.ailighting.auth.exception.BaseBusinessException;
import com.kinglumi.ailighting.auth.mapper.MeshInfoMapper;
import com.kinglumi.ailighting.auth.mapper.MeshUserLinkMapper;
import com.kinglumi.ailighting.auth.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Lxin
 * @version 1.0
 * @date 2021/8/9 11:17
 */
@Service
@Slf4j
public class UserInfoService extends BaseService<UserMapper, UserInfo> {

    @Resource
    private MeshUserLinkMapper meshUserLinkMapper;
    @Resource
    private UserMapper userMapper;

    @Resource
    private MeshInfoMapper meshInfoMapper;


    @Override
    public ApiResult selectPageByQuery(Query query) {
        Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
        List<UserInfo> userInfos = this.mapper.selectByExample(this.query2example(query, false));
        if (CollectionUtils.isEmpty(userInfos)) {
            return ApiResult.okPage();
        }
        List<Integer> userId = userInfos.stream().map(UserInfo::getId).collect(Collectors.toList());
        Example mes = new Example(MeshUserLink.class);
        mes.createCriteria().andIn("userId", userId);
        List<MeshUserLink> meshUserLinks = meshUserLinkMapper.selectByExample(mes);
        Map<Integer, List<MeshUserLink>> map = meshUserLinks.stream().collect(Collectors.groupingBy(MeshUserLink::getUserId));
        if (!CollectionUtils.isEmpty(map)) {
            for (UserInfo info : userInfos) {
                info.setMeshCount(map.get(info.getId()) == null ? 0 : map.get(info.getId()).size());
                info.setMeshList(map.get(info.getId()) == null ? new ArrayList<>() : map.get(info.getId()).stream().map(MeshUserLink::getMeshId).collect(Collectors.toList()));
            }
        }
        return ApiResult.okPage(userInfos, result.getTotal());
    }

    public int getNewUserCount() {
        return userMapper.getNewUserCount();
    }

    /**
     * 删除用户
     *
     * @param userId
     */
    public void deleteUser(Integer userId, Boolean flag) {
        if (userId == null) {
            throw new BaseBusinessException(ServiceErrorEnum.PARAMETER_IS_EMPTY);
        }
        if(flag){
            UserInfo loginUserId = getLoginUserId();
            Boolean isAdmin = loginUserId.getIsAdmin();
            if (!isAdmin) {
                throw new BaseBusinessException(ServiceErrorEnum.NOT_ADMIN);
            }
        }
        // 先删除 关联mesh
        meshUserLinkMapper.deleteByUserId(userId);
        List<MeshInfo> meshInfos = meshInfoMapper.selectByUserId(userId);
        if (Objects.nonNull(meshInfos)) {
            // 存在 删除 关联里面的 mesh
            List<Integer> meshIds = meshInfos.stream().map(MeshInfo::getId).collect(Collectors.toList());
            for (Integer meshId : meshIds) {
                // 删除 关联的
                meshUserLinkMapper.deleteByMeshId(meshId);
            }
        }
//        // 删除管理的 mesh
        meshInfoMapper.deleteByUserId(userId);
//        // 删除自己
        userMapper.deleteByUserId(userId);
    }

    /**
     * 获取登录用户Id
     *
     * @return 用户Id
     */
    private UserInfo getLoginUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetail principal = (UserDetail) authentication.getPrincipal();
        return principal.getUserInfo();
    }
}

